package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fsd.admin.dao.B_articleDao;
import com.fsd.admin.dao.Z_articlefzDao;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_article;
import com.fsd.admin.model.Z_articlefz;
import com.fsd.admin.service.B_articlerelateService;
import com.fsd.admin.service.Z_articlefzService;
import com.fsd.admin.service.Z_zwftglService;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.BeanToMapUtil;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.google.gson.Gson;

@Repository("Z_zwftglServiceImpl")
public class Z_zwftglServiceImpl extends MainServiceImpl<Z_articlefz, String> implements Z_zwftglService {

	private static final Logger log = Logger.getLogger(Z_articlefzServiceImpl.class);
    private String depict = "政务访谈管理";

    @Resource(name = "z_articlefzDaoImpl")
	public void setBaseDao(Z_articlefzDao Z_articlefzDao) {
		super.setBaseDao(Z_articlefzDao);
	}
    
    @Resource(name = "z_articlefzDaoImpl")
	private Z_articlefzDao objectDao;
    
    @Resource(name = "b_articleDaoImpl")
	private B_articleDao articleDao;
    
    @Resource(name = "b_articlerelateServiceImpl")
	private B_articlerelateService articleRelateService;
    
    @Resource(name = "z_articlefzServiceImpl")
	private Z_articlefzService articleFzService;
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param) throws Exception{
		Criteria c = articleDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("type", "wzft"));
		c.addOrder(Order.desc("adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("title") != null && !"".equals(objectMap.get("title"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("title") + "%"));
			}
		}
		return articleDao.findPager(param , c);
	}
	
	/**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public ParametersUtil save(Z_articlefz obj, A_Employee employee, B_article article, ParametersUtil param) throws Exception{
		 if(obj.getId() != null && !"".equals(obj.getId())){
	            //修改
	            B_article old_article = articleDao.get(article.getId());
	            old_article.setSubjectid(article.getSubjectid());//设置修改所属栏目id
	            old_article.setSubjectname(article.getSubjectname());//设置修改栏目名称
	            old_article.setType(article.getType());//设置修改类型code
	            old_article.setTypename(article.getTypename());//设置修改类型名称
	            old_article.setSubtitle(article.getSubtitle());//设置修改副标题
	            old_article.setTitle(article.getTitle());//设置修改标题
	            old_article.setShowtitle(article.getShowtitle());//设置修改显示标题
	            old_article.setTitlecolor(article.getTitlecolor());//设置修改标题颜色
	            old_article.setRecommend(article.getRecommend());//设置修改推荐
	            old_article.setVideo(article.getVideo());//设置修改视频
	            old_article.setRoll(article.getRoll());//设置修改滚动
	            old_article.setHeadline(article.getHeadline());//设置修改头条
	            old_article.setHot(article.getHot());//设置修改热门
	            old_article.setComments(article.getComments());//设置修改评论
	            old_article.setKeyword(article.getKeyword());//设置修改关键字
	            old_article.setAurl(article.getAurl());//设置修改外链接
	            old_article.setIsaurl(article.getIsaurl());//设置修改是否外链接
	            old_article.setAuthor(article.getAuthor());//设置修改作者
	            old_article.setSource(article.getSource());//设置修改来源
	            old_article.setShowtype(article.getShowtype());//设置修改显示类型code
	            old_article.setShowtypename(article.getShowtypename());//设置修改显示类型名称
	            old_article.setOverdue(article.getOverdue());//设置修改过期时间
	            old_article.setAbstracts(article.getAbstracts());//设置修改简介
	            old_article.setContent(article.getContent());//设置修改内容
	            old_article.setImageurl1(article.getImageurl1());//设置修改标题图片1
	            old_article.setImageurl2(article.getImageurl2());//设置修改标题图片2
	            old_article.setVideourl(article.getVideourl());//设置修改内容视频
	            old_article.setVoiceurl(article.getVoiceurl());//设置修改内容语音
	            old_article.setWordnum(article.getWordnum());//设置修改文章字数
	            old_article.setImagenum(article.getImagenum());//设置修改照片数
	            old_article.setSort(article.getSort());//设置修改序号
	            old_article.setAuditing("false");//标记未审批
	            old_article.setUpdatedate(this.getData());
	            old_article.setUpdateemployeeid(employee.getId());
	            old_article.setUpdateemployeename(employee.getRealname());
				if (article.getAdddate() != null && !article.getAdddate().equals("")
					&& article.getAdddate().length() == 14){
					old_article.setAdddate(article.getAdddate());
				}
//				if (!"true".equals(article.getFirstly())){
//					old_article.setFirstly("false");//设置修改置顶
//				}
//				if (!"true".equals(article.getSlide())){
//					old_article.setSlide("false");//设置修改幻灯
//				}
	            articleDao.update(old_article);
	            
	            Z_articlefz fz_old_obj = articleFzService.getObjectByArticleId(obj.getId());
	            fz_old_obj.setMc(obj.getMc());//设置修改名称
	            fz_old_obj.setFwsj(obj.getFwsj());//设置修改发文时间
	            fz_old_obj.setFwjg(obj.getFwjg());//设置修改发文机构
	            fz_old_obj.setUpdatedate(this.getData());//设置修改日期
	            fz_old_obj.setUpdateemployeeid(employee.getId());//设置修改用户id
	            fz_old_obj.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
				objectDao.update(fz_old_obj);
	        }else{
	            //添加
				article.setId(this.getUUID());//设置主键
				article.setCompanyid(employee.getCompanyid());//所属单位
				article.setAuditing("false");//标记未审批
				article.setAdddate(this.getData());//设置添加日期
				article.setAddemployeeid(employee.getId());//设置添加用户id
				article.setAddemployeename(employee.getRealname());//设置添加用户姓名
				article.setDeleted("0");//设置删除标志(0:正常 1: 已删除)
				if (article.getAdddate() == null || article.getAdddate().length() != 14){
					article.setAdddate(this.getData());
				}
				if (!"true".equals(article.getFirstly())){
					article.setFirstly("false");
				}
				if (!"true".equals(article.getSlide())){
					article.setSlide("false");
				}
				articleDao.save(article);
				
				Z_articlefz fz_old_obj = new Z_articlefz();
				
				fz_old_obj.setId(this.getUUID());//设置主键
				fz_old_obj.setCompanyid(employee.getCompanyid());//所属单位
				fz_old_obj.setAdddate(this.getData());//设置添加日期
				fz_old_obj.setAddemployeeid(employee.getId());//设置添加用户id
				fz_old_obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
				fz_old_obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
				fz_old_obj.setArticleid(article.getId());
				objectDao.save(fz_old_obj);
	        }
	        if(param.getJsonData() != null && !"".equals(param.getJsonData())){
				articleRelateService.delObject(article.getId(), Config.ARTICLERELATESUBJECT);
				articleRelateService.delObject(article.getId(), Config.ARTICLERELATESUBJECTXG);
				Gson gs = new Gson();
				Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
				ArrayList<String> sidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECT);
				ArrayList<String> sxgidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECTXG);
				if (sidList.size() > 0){
					for (String id : sidList) {
						articleRelateService.saveArticleRelate(article.getId(), id, Config.ARTICLERELATESUBJECT);
					}
				}
				if (sxgidList.size() > 0){
					for (String id : sxgidList) {
						articleRelateService.saveArticleRelate(article.getId(), id, Config.ARTICLERELATESUBJECTXG);
					}
				}
			}
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + article.getId() + article.getTitle(), employee, Z_articlefzServiceImpl.class);
			ParametersUtil util = new ParametersUtil();
			util.addSendObject("id", article.getId());
			return util;
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		String hql = "";
		objectDao.executeHql("update B_article t set t.deleted = '1', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 修改状态
	 * @param parameters
	 */
	public void updateEnabledObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		if (isEnabled)
			objectDao.executeHql("update B_article t set t.auditing = 'true' where t.id in (" + ids + ")");
		else
			objectDao.executeHql("update B_article t set t.auditing = 'false' where t.id in (" + ids + ")");
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_articlefz obj = this.getObjectByArticleId(objectMap.get("id").toString());
		B_article article = articleDao.get(objectMap.get("id").toString());
		if(obj == null || article == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		Map<String, String> map = BeanToMapUtil.convertBean(article);
		map.put("mc", obj.getMc());
		map.put("fwsj", obj.getFwsj());
		map.put("fwjg", obj.getFwjg());
		
		ParametersUtil util = new ParametersUtil();
		util.addSendObject("data", map);
		util.addSendObject(Config.ARTICLERELATESUBJECT, 
				articleRelateService.getObjectIDList(article.getId(), Config.ARTICLERELATESUBJECT));
		util.addSendObject(Config.ARTICLERELATESUBJECTXG, 
				articleRelateService.getObjectIDList(article.getId(), Config.ARTICLERELATESUBJECTXG));
   		return util;
	}
	
	/**
	 * 根据文章ID加载对象
	 * @param articleId
	 * @return
	 * @throws Exception
	 */
	public Z_articlefz getObjectByArticleId(String articleId) throws Exception{
		List<Z_articlefz> list = objectDao.queryByHql("from Z_articlefz where articleid = ?", articleId);
		if(list.size() > 0){
			return list.get(0);
		}
		return null;
	}
}
